close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com






PHP - Variables

  • Variables are reserved memory locations for storing data values.
  • In PHP, all variables starts with the $ sign, followed by the name of the variable.
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A PHP variable name cannot contain spaces.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • PHP variable names are case-sensitive.($code and $CODE are two different variables)
  • Assignment of variables are done with assignment operator, “equal to (=)”.
  • PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.
  • Let's see the example to store string, integer, and float values in PHP variables.


    Example : Declaring string, integer, and float

    
    <?php  
    $str="hello string";  
    $x=123;  
    $y=345.6;  
    echo "string is: $str 
    "; echo "integer is: $x
    "; echo "float is: $y
    "; ?>

    Global Scope

    A variable declared outside a function has a Global Scope and can only be accessed outside a function


    Example : Global Scope

    
     <?php              
     $x = 78; // global scope
     function myTest() {
       echo "Variable x inside function is: $x";
     } 
     myTest();
     echo "Variable x outside function is: $x";
     ?>




    use the global keyword to access a global variable from within a function.


    Example : Global Keyword

    
     <?php              
     $x = 78; // global scope
     function myTest() {
        global $x;
       echo "Variable x inside function is: $x";
     } 
     myTest();
     echo "Variable x outside function is: $x";
     ?>

    Local Scope

    A variable declared within a function has a Local Scope and can only be accessed within that function:


    Example : Local Scope

    
     <?php              
     function myTest() {
        $x = 78; // local scope 
       echo "Variable x inside function is: $x";
     } 
     myTest();
     echo "Variable x outside function is: $x";
     ?>